<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="角色名称:">
        <el-input
          placeholder="请输入角色名称"
          v-model="keyword"
          @keyup.enter="search"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="keyword ? false : true" @click="search"
          >搜索</el-button
        >
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" icon="Plus" @click="addRole">添加职位</el-button>
    <el-table border style="margin: 10px 0" :data="allRole">
      <el-table-column
        align="center"
        label="#"
        type="index"
        width="180px"
      ></el-table-column>
      <el-table-column align="center" label="ID" prop="id"></el-table-column>
      <el-table-column
        align="center"
        label="职位名称"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template #="{ row }">
          <el-button type="primary" icon="User" size="small" @click="setPermission(row)"
            >分配权限</el-button
          >
          <el-button type="primary" icon="Plus" size="small" @click="updateRole(row)"
            >编辑</el-button
          >
          <el-popconfirm
            :title="`你确定要删除${row.roleName}?`"
            width="260px"
            @confirm="removeRole(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getAllRole"
      @size-change="sizeChange"
    />
  </el-card>
  <!-- 对话框，显示添加职位 -->
  <el-dialog
    v-model="dialogTableVisible"
    :title="roleParams.id ? '修改职位' : '添加职位'"
    align-center
    draggable
    center
  >
    <el-form ref="formRef" :rules="rules" :model="roleParams">
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          placeholder="请输入想添加的职位名称"
          v-model="roleParams.roleName"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="dialogTableVisible = false"
        >取消</el-button
      >
      <el-button type="primary" size="default" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉：展示用户职位的权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配职位权限与按钮权限</h4>
    </template>
    <template #default>
      <el-tree
        ref="tree"
        style="max-width: 600px"
        :data="menuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="[5]"
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import useLayOutSettingStore from "@/store/modules/setting";
import type { Records, RoleData, MenuResponseData, MenuList } from "@/api/acl/role/type";
import {
  reqAllRole,
  reqAddOrUpdateRole,
  reqAllPermission,
  reqSetPermisstion,
  reqRemoveRole,
} from "@/api/acl/role";
import { ElMessage } from "element-plus";
// 初始化settingStore
let settingStore = useLayOutSettingStore();
// 初始化分页
let pageNo = ref<number>(1);
let pageSize = ref<number>(10);
// 定义初始关键字
let keyword = ref<string>("");
// 初始化总页数
let total = ref<number>(0);
// 初始化全部职位
let allRole = ref<Records>([]);
// 初始化对话框
let dialogTableVisible = ref<boolean>(false);
// 初始化添加职位数据
let roleParams = reactive<RoleData>({
  roleName: "",
});
// 初始化表单实例
let formRef = ref<any>();
// 控制抽屉的显示与隐藏
let drawer = ref<boolean>(false);
// 初始化全部权限及按钮权限
let menuArr = ref<MenuList>([]);
//准备一个数组:数组用于存储勾选的节点的ID(四级的)
let selectArr = ref<number[]>([]);

// 初始化树形控件实例
let tree = ref();

// 组件挂载完毕，发送请求
onMounted(() => {
  getAllRole();
});

// 获取全部职位的方法
const getAllRole = async (pager = 1) => {
  let result: any = await reqAllRole(pager, pageSize.value, keyword.value);
  if (result.code === 200) {
    total.value = result.data.total;
    allRole.value = result.data.records;
  }
};

// 分页器下拉框变化时触发的回调
const sizeChange = () => {
  getAllRole();
};
// 搜索按钮触发的回调
const search = () => [getAllRole()];
// 点击重置按钮触发的回调
const reset = () => {
  settingStore.refsh = !settingStore.refsh;
};
// 点击添加职位按钮的回调
const addRole = () => {
  //清空数据
  Object.assign(roleParams, {
    roleName: "",
    id: 0,
  });
  //清空上一次表单校验错误结果
  nextTick(() => {
    formRef.value.clearValidate("roleName");
  });
  dialogTableVisible.value = true;
};
// 点击编辑按钮的回调
const updateRole = (row: RoleData) => {
  dialogTableVisible.value = true;
  Object.assign(roleParams, row);
  //清空上一次表单校验错误结果
  nextTick(() => {
    formRef.value.clearValidate("roleName");
  });
};

// 自定义校验规则回调
const validatorRoleName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error("职位名称至少两位"));
  }
};
// 自定义表单校验规则

const rules = {
  roleName: [{ required: true, trigger: "blur", validator: validatorRoleName }],
};
// 点击确定按钮的回调
const save = async () => {
  // 自定义校验规则，不满足不往下执行
  await formRef.value.validate();
  let result: any = await reqAddOrUpdateRole(roleParams);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: roleParams.id ? "修改成功" : "添加成功",
    });
    // 刷新ui
    getAllRole(roleParams.id ? pageNo.value : 1);
  } else {
    ElMessage({
      type: "error",
      message: roleParams.id ? "修改失败" : "添加失败",
    });
  }

  dialogTableVisible.value = false;
};
// 点击分配权限按钮的回调
const setPermission = async (row: RoleData) => {
  // 显示抽屉
  drawer.value = true;
  // 存储数据
  Object.assign(roleParams, row);
  let result: MenuResponseData = await reqAllPermission(roleParams.id as number);
  if (result.code == 200) {
    menuArr.value = result.data;
    selectArr.value = filterSelectArr(menuArr.value, []);
  }
};
// 筛选选中id的方法
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr);
    }
  });
  return initArr;
};

const defaultProps = {
  children: "children",
  label: "name",
};
// 点击确定按钮的回调
const handler = async () => {
  // 收集选中职位的id 这是原本的
  const userId = roleParams.id as number;
  //选中节点的ID 这是新增的
  let arr = tree.value.getCheckedKeys();
  //半选的ID -- 选中节点的父级 也就是复选框为半选状态的
  let arr1 = tree.value.getHalfCheckedKeys();
  let permissionId = arr.concat(arr1);
  // 发送请求，更新数据
  let result: any = await reqSetPermisstion(userId, permissionId);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "分配权限成功",
    });
    // 抽屉关闭
    drawer.value = false;
    // 重新加载数据
    // 这里要注意的是，当修改完权限之后，不同用户看到的界面是不一样的，需要重新获取数据
    window.location.reload();
  }
};

// 点击删除按钮的回调
const removeRole = async (id: number) => {
  let result: any = await reqRemoveRole(id);
  if (result.code == 200) {
    //提示信息
    ElMessage({ type: "success", message: "删除成功" });
    getAllRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }
};
</script>
<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
